package controllers

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "k8s-api/kubeclient"
    v1 "k8s.io/api/apps/v1"
    "net/http"
)

func GetDeploymentHandler(c *gin.Context) {
    kubeController := &kubeclient.DeploymentKubeController{KubeController: kubeclient.K8sMap["k8s"]}
    namespace := c.Param("namespace")
    deploymentName := c.Param("deployment")
    data, err := kubeController.Get(namespace, deploymentName)
    if err != nil {
        fmt.Println("获取Deployment异常", err)
    }

    c.JSON(http.StatusOK, gin.H{
        "data": data,
    })
}

func CreateDeploymentHandler(c *gin.Context) {

    kubeController := &kubeclient.DeploymentKubeController{KubeController: kubeclient.K8sMap["k8s"]}
    namespace := c.Param("namespace")
    deploymentName := c.Param("deployment")
    var deployment = &v1.Deployment{}
    err := c.BindJSON(deployment)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "code": http.StatusInternalServerError,
            "message": "Body无法转化为Deployment",
        })
        return
    }

    data, err := kubeController.Create(namespace, deploymentName, deployment)
    if err != nil {
        fmt.Println("创建Deployment异常", err)
    }

    c.JSON(http.StatusOK, gin.H{
        "data": data,
    })
}

func DeleteDeploymentHandler(c *gin.Context) {
    kubeController := &kubeclient.DeploymentKubeController{KubeController: kubeclient.K8sMap["k8s"]}
    namespace := c.Param("namespace")
    deploymentName := c.Param("deployment")

    err := kubeController.Delete(namespace, deploymentName)
    if err != nil {
        fmt.Println("创建Deployment异常", err)
    }

    c.JSON(http.StatusOK, gin.H{
        "data": "ok",
    })
}
func UpdateDeploymentHandler(c *gin.Context) {

    kubeController := &kubeclient.DeploymentKubeController{KubeController: kubeclient.K8sMap["k8s"]}
    namespace := c.Param("namespace")
    deploymentName := c.Param("deployment")
    var deployment = &v1.Deployment{}
    err := c.BindJSON(deployment)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "code": http.StatusInternalServerError,
            "message": "Body无法转化为Deployment",
        })
        return
    }

    data, err := kubeController.Update(namespace, deploymentName, deployment)
    if err != nil {
        fmt.Println("更新Deployment异常", err)
    }

    c.JSON(http.StatusOK, gin.H{
        "data": data,
    })
}